import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { constantRouterMap, asyncRouterMap } from '@/config/router.config'

/**
 * 提取末级路由
 */
const extractRoute = (arr) => {
  const result = []
  const fn = (list) => {
    list.forEach(item => {
      if (item.children?.length) {
        fn(item.children)
      } else {
        result.push(item)
      }
    })
  }
  fn(arr)
  return result
}
// hack router push callback
const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(Router)
const createRouter = (routes, mode) =>
  new Router({
    mode: mode || 'history',
    scrollBehavior: () => ({ y: 0 }),
    routes: routes || (!window.__POWERED_BY_QIANKUN__ ? constantRouterMap.concat(asyncRouterMap) : constantRouterMap.concat(extractRoute(asyncRouterMap)))
  })

let router

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
const resetRouter = (routes, mode) => {
  const newRouter = createRouter(routes, mode)
  router.matcher = newRouter.matcher // reset router
  return router
}

const pathReplace = (base, data) => {
  data = data.map((item) => {
    if (!item.path.includes(base) && item.path.indexOf('/') === 0) {
      item.path = base + item.path
    }
    if (item.redirect && !item.redirect.includes(base) && item.redirect.indexOf('/') === 0) {
      item.redirect = base + item.redirect
    }
    if (item.children) {
      item.children = pathReplace(base, item.children)
    }
    item.meta = item.meta || {}
    item.meta.basePath = base
    return item
  })
  return data
}
const routerPathQK = (base, routes) => {
  routes = routes || asyncRouterMap // constantRouterMap.concat(asyncRouterMap)
  routes = pathReplace(base, routes)
  return routes
}

if (window.__POWERED_BY_QIANKUN__) {
  console.log(store.getters.portalType)
  const portalType = store.getters.portalType
  if (portalType === 'portalYth') {
    const routes = routerPathQK('/portalCenter/gzt-admin')
    router = createRouter(routes, 'hash')
  } else {
    router = createRouter()
  }
} else {
  router = createRouter()
}

export default router
export { createRouter, resetRouter }
